package com.atguigu.gulimail.product.webController;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gulimail.product.annotation.RequstLogAnnotation;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.gulimail.product.util.ProductUtils;
import com.atguigu.gulimail.product.vo.CataLog2Vo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Fengkai
 * @creat 2022/1/29
 */
@Slf4j
@Controller
public class ViewController {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping({"/", "/index"})
    public String getIndex(Model model){
        //查询一级分类信息
        List<CategoryEntity> categories = categoryService.selectCategoryLevl1();
        model.addAttribute("categories",categories);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    @RequstLogAnnotation
    public Map<String, List<CataLog2Vo>> getCatalogJson(){
        Map<String, List<CataLog2Vo>> catalogJson = null;
        try {
            catalogJson = categoryService.getCatalogJson();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return catalogJson;
    }

    @Transactional()
    @ResponseBody
    @GetMapping("/getredislock")
    public String getRedisLock(){
        RLock lock = redissonClient.getLock("redissonLock");
        lock.lock(30 , TimeUnit.SECONDS);
        System.out.println("线程:" + Thread.currentThread().getId() + "获取了锁");

        try {
            ProductUtils.test();
            log.error("测试error级别日志");
            log.debug("测试debug级别日志");
            log.info("测试info级别日志");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            log.info("释放锁---》线程id,{}", Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }
}
